// app.js
App({
  data: {
    navs:[
      {title: "首页",class:"", path:"/pages/index/index", icon: "", font: "fa fa-home"},
      {title: "社区",class:"", path:"", icon: "", font: "fa fa-comments-o"},
      // {title: "维修",class:"", path:"", icon: "", font: "fa fa-wrench"},
      {title: "我的",class:"co", path:"/pages/mine/mine", icon: "", font: "fa fa-user-circle"},
    ],
  },
  onLaunch: function () {
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      wx.cloud.init({
        // env 参数说明：
        //   env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境（第一个创建的环境）
        // env: 'my-env-id',
        traceUser: true,
      });
    }

    this.globalData = {
      host: "https://cqtp.int-great.cn",
      // host: "https://spgs.int-great.cn",
      after_login:[]
    };
    this.doLogin();
  },
  afterLogin(vm, fun) {
    let ev = [vm,fun];
    this.globalData.after_login.push(ev);
  },
  logined(){
    let v = this;
    let ll = this.globalData.after_login || [];
    for(let i = 0, il = ll.length; i< il; i++) {
      let ev = ll[i];
      if(ev[0] && ev[1] && (typeof ev[1] == 'function')) {
        ev[1].call(ev[0]);
      }
    }
    console.log('logined');
  },
  doLogin(vm, cb){
    let v = this;
    let url = v.globalData.host + '/api/weixin/login';
    wx.login({
      success (res) {
        if (res.code) {
          wx.request({ url: url, data: { code: res.code },success (res){
            let r = res.data;
            if(r.code == 200 && r.data) {
              v.globalData.token = r.data.token;
              v.globalData.userInfo = r.data.userInfo;
              if(cb && typeof cb == 'function') {
                cb.call(vm || {}, r.data);
              }
              v.logined();
            } else {
              wx.showToast({ title: r.msg, icon: 'none' })
            }
          } })
        } else {
          wx.showToast({ title: res.errMsg, icon: 'none' })
        }
      }
    })
  },
  ymd(dt) {
    if (typeof dt == 'string') dt = new Date(dt);
    if (typeof dt == 'number') dt = new Date(dt);
    if (!dt) dt = new Date();
    if (!dt.getFullYear) dt = new Date();
    let yy = dt.getFullYear();
    let mm = dt.getMonth() + 1;
    let dd = dt.getDate();
    if (mm < 10) mm = '0' + mm;
    if (dd < 10) dd = '0' + dd;
    let ymd = '' + yy + '-' + mm + '-' + dd;
    return ymd;
  }
});
